#include "MobileSDK.h"
#include "Crypt.h"
#include "eikenv.h"

EXPORT_C CMobileSDK::CMobileSDK()
{
	iRequestIap = 0;
	iClient = NULL;
	qwfilepath = NULL;
}

EXPORT_C CMobileSDK::~CMobileSDK()
{
	if( iClient )
	{
		delete iClient;
		iClient = NULL;
	}
	
	DELETE(qwfilepath);
}

/**
 * �����ṩ�ĳ�ʼ������
 */
EXPORT_C void CMobileSDK::OnInit(TUint aIapID)
{ 
	QBOOL flag = QFALSE;
	if( iClient )
	{
		delete iClient;
		iClient = NULL;
	}
	iClient = CClientEngine::NewL(*this);

	iRequestIap = aIapID;
	
	//�õ���Ҫд��¼��·��
	GetFilePath();
			
	//ִ���ļ�����
    if(FileOperation(strsend,0)){
		//ִ�з�����ݲ���
		flag = PostSend(strsend);
	}
			
	//����ͳɹ���ִ��ɾ�����
	if(flag){
		FileDelete();
	}
}

//�����ṩ�ĸ�����ݺ���
EXPORT_C void CMobileSDK::updateActionData(char* actionType,char* actionData)
{
	QBOOL flag =QFALSE;
	
	//�õ�JSON�ַ�
	GetSendJson(actionType,actionData,strsend);
	
	//�õ���Ҫд��¼��·��
    GetFilePath();
		
	//ִ���ļ�����
    if(FileOperation(strsend,1)){
    	//ִ�з�����ݲ���
    	flag = PostSend(strsend);
    }
    			
    //����ͳɹ���ִ��ɾ�����
    if(flag){
    	FileDelete();
    }
}

QVOID CMobileSDK::GetSendJson(LPSTR actionType,LPSTR actionData,CQSString &qstring)
{
	qstring.Empty();
	
	//============================================================
	CQWString wstrIMEI;
	CQWString wstrMan;
	CQWString wstrModel;
	CImeiEngine::GetIMEIL(wstrIMEI, wstrMan, wstrModel);
	CQSString strDeviceId;
	strDeviceId.SetData(&wstrIMEI);
	
	wstrMan.AppendChar(' ');
	wstrMan.AppendData((QPBYTE)wstrModel.GetDataPtr(), wstrModel.GetLength());
	CQSString strDeviceDetail;
	strDeviceDetail.SetData(&wstrMan);
	
	TPtrC8 inMD5;
	inMD5.Set((unsigned char*) (strDeviceId.GetDataPtr()), strDeviceId.GetLength());

//	TBuf<32> forShow;
//	forShow.Copy(inMD5);
//	CEikonEnv::InfoWinL(_L("OK"),forShow);
	
	TBuf8<32> desoutMD5;
	CCrypt::MD5HashHexString(inMD5, desoutMD5); //md5���ܲ�תδHEX�ַ�
	CQSString tmpcid;
	tmpcid.SetData((QPBYTE)desoutMD5.Ptr(), desoutMD5.Length());
	CQSString strcid;
	strcid.SetData( (unsigned char*)(tmpcid.GetDataPtr() + 7), 12);
	
	CQWString wstrIMSI;
	CImsiEngine::GetIMSIL(wstrIMSI);
	CQSString strIMSI;
	strIMSI.SetData(&wstrIMSI);
	
	CQWString wstrMAC;
	CSystemCall::GetWLanMacAddress(wstrMAC);
	CQSString strMAC;
	strMAC.SetData(&wstrMAC);
	
	CQSString strPhoneOS;
	CSystemCall::GetPhoneNameString(strPhoneOS);	//S60
	
	//CQSString strApn;
	//CSystemCall::GetOutGoingApn(strApn);
	//strApn.AppendData("cmnet");
	
	CQSString strUID;
	CSystemCall::GetUId(strUID);
	
	CQSString strTimeStamp;
	QUINT nTime = CSystemCall::GetCurrentTimeToInt();
	strTimeStamp.ToString(nTime);
	
	//�ж�aIapID�Ƿ�Ϸ����Ϸ�����ΪĬ�Ͻ����
	CQSString strAPNName;
	if((iRequestIap >= 0) && (CSystemCall::GetOutGoingApn(iRequestIap, strAPNName) ))
	{
		iClient->iRequestIap = iRequestIap;
	}
	else	//ȡĬ�Ͻ��������
	{
		TUint32 nDefaultIAPID = CSystemCall::GetPreferceIap();
		CSystemCall::GetOutGoingApn(nDefaultIAPID, strAPNName);
	}
	
	TSize screensize = CSystemCall::GetScreenSizeInPixel();
	CQSString strWidth;
	CQSString strHeight;
	strWidth.ToString(screensize.iWidth);
	strHeight.ToString(screensize.iHeight);
	//============================================================
	
	qstring.AppendData("{");
	
	qstring.AppendData("\r\n");	
	
	//����json����Ϣ��
	qstring.AppendData("\"protocolVersion\":");
	qstring.AppendData("\"1\",");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("\"sdkVersion\":");
	qstring.AppendData("\"0\",");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("\"cid\":\"");
	qstring.AppendData((QPBYTE)strcid.GetDataPtr(), strcid.GetLength());
	qstring.AppendData("\",");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("\"appKey\":");
	qstring.AppendData("\"123213232\",");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("\"channel\":\"");
	TBuf<8> desCM;
	desCM.Fill(0,8);
	desCM = _L("中国移动");//_L("z:\\resource\\apps\\MQZone");//_L("�й��ƶ�");
	CQWString wstrChinaMobile;
	wstrChinaMobile.SetData((wchar_t*)desCM.Ptr(), desCM.Length());
	CQSString strChinaMobile;
	strChinaMobile.SetData(&wstrChinaMobile);
	qstring.AppendData((QPBYTE)strChinaMobile.GetDataPtr(), strChinaMobile.GetLength());
	qstring.AppendData("\",");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("\"versionName\":");
	qstring.AppendData("\"1.0\",");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("\"versionCode\":");
	qstring.AppendData("\"1010\",");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("\"packageName\":\"");
	qstring.AppendData((QPBYTE)strUID.GetDataPtr(), strUID.GetLength());
	qstring.AppendData("\",");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("\"ip\":");
	qstring.AppendData("\"127.0.0.1\",");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("\"deviceDetail\":\"");
	qstring.AppendData((QPBYTE)strDeviceDetail.GetDataPtr(), strDeviceDetail.GetLength());
	qstring.AppendData("\",");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("\"phoneOs\":\"");
	qstring.AppendData((QPBYTE)strPhoneOS.GetDataPtr(), strPhoneOS.GetLength());
	qstring.AppendData("\",");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("\"imsi\":\"");
	qstring.AppendData((QPBYTE)strIMSI.GetDataPtr(), strIMSI.GetLength());
	qstring.AppendData("\",");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("\"deviceId\":\"");
	qstring.AppendData((QPBYTE)strDeviceId.GetDataPtr(), strDeviceId.GetLength());
	qstring.AppendData("\",");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("\"mac\":\"");
	qstring.AppendData((QPBYTE)strMAC.GetDataPtr(), strMAC.GetLength());
	qstring.AppendData("\",");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("\"accessPointName\":\"");
	qstring.AppendData((QPBYTE)strAPNName.GetDataPtr(), strAPNName.GetLength());
	qstring.AppendData("\",");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("\"screenWidth\":\"");
	qstring.AppendData((QPBYTE)strWidth.GetDataPtr(), strWidth.GetLength());
	qstring.AppendData("\",");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("\"screenHeight\":\"");
	qstring.AppendData((QPBYTE)strHeight.GetDataPtr(), strHeight.GetLength());
	qstring.AppendData("\",");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("\"sendTime\":\"");
	qstring.AppendData((QPBYTE)strTimeStamp.GetDataPtr(), strTimeStamp.GetLength());
	qstring.AppendData("\",");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("\"actionType\":\"");
	qstring.AppendData(actionType);
	qstring.AppendData("\",");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("\"actionData\":\"");
	qstring.AppendData(actionData);
	qstring.AppendData("\"");
	qstring.AppendData("\r\n");	
	
	qstring.AppendData("}");
}

/**
 * ִ��post����
 */
EXPORT_C QBOOL CMobileSDK::PostSend(CQSString& cqstring)
{
	QBOOL flag = QFALSE;
	if( iClient == NULL ){
	   return flag;
	}
	
	iClient->CancelTransaction();
	
	//TBufC8<256> uri8 (_L8("http://121.15.167.233:8080/UserAttribute/QueryServlet"));
	TBufC8<256> uri8 (_L8("http://221.176.9.104:8022/SymbianSDK?func=mmsdk:posteventlog"));
	_LIT8(KMimeType, "text/plain");
	
	CQSString strBase64;
	CSystemCall::EncodeL(cqstring, strBase64);
	
	HBufC8* bufToSend = HBufC8::NewL(strBase64.GetLength());

	bufToSend->Des().Append((TUint8*)strBase64.GetDataPtr(), strBase64.GetLength());
	//bufToSend->Copy((TUint8*)qstring->GetDataPtr(), qstring->GetLength());
	
	iClient->IssueHTTPPostL(uri8, KMimeType, bufToSend->Des());

	delete bufToSend;
	
	return QTRUE;
}

QVOID CMobileSDK::GetFilePath(){
	CQSString cqstrfile;
	cqstrfile.Empty();
	cqstrfile.SetData("c:\\1.txt");
	if(qwfilepath!=NULL){
	   DELETE(qwfilepath);
	}
	qwfilepath = new CQWString(cqstrfile);
}

/**
 * ɾ���ļ�����
 */
QBOOL CMobileSDK::FileDelete(){
	QBOOL flag = QFALSE;
	CQFile* file = new CQFile();
	flag = file->DeleteFile(qwfilepath->GetDataPtr());
	DELETE(file);
	return flag;
}

/**
 * ���ļ����в���
 * CQWString& path �ļ���·��
 * QINT QFlag 1������д�ļ�����������ִ���ļ�д
 */
EXPORT_C QBOOL CMobileSDK::FileOperation(CQSString& cqstring,QINT QFlag){
	CQFile* file = new CQFile();
	
	//���ļ�����
	if(file->Open(qwfilepath->GetDataPtr(),CQFile::modeReadWrite)){
	    
	    //�����update��������ֻ��Ҫ�����ļ�����
	    if(QFlag==1){
	         QINT filelength = file->GetLength();
	         if(filelength>0){
	         
	              //���ļ�����
	              LPSTR p_string = new char[filelength];
	        	  QINT  contentlength = file->Read(p_string,filelength);
	        	  CQSString filestring;
	        	  filestring.Empty();
	        	  filestring.AppendData(p_string);
	        	 	        	  
	        	  //ִ���ļ��رղ���
	        	  file->Close();
	        	  
	        	  //ִ��ɾ���ļ�����
	        	  file->DeleteFile(qwfilepath->GetDataPtr());
	        	  
	        	  //���´��ļ�����
	        	  file->Open(qwfilepath->GetDataPtr(),CQFile::modeWrite);
	        	  
	        	  if(contentlength>0){
	        	       
	        	  	   QINT  linelength=0;//��¼������
	        	  	    	 	 
	        	  	   //�õ���¼����
	        	  	   QINT  lastlength = 0;//������ڵ�λ��
	        	  	   while(contentlength>lastlength){
	        	  	        lastlength = filestring.Find("}",lastlength);
	        	  	        lastlength ++;//�ƶ�����һ��δ֪
	        	  	    	if(lastlength > 0){
	        	  	    	  linelength ++;
	        	  	    	}else{
	        	  	    	    break;
	        	  	    	}
	        	  	   }
	        	  	   
	        	  	   //�ж��ļ��������ǲ��Ǵ���3����������������
	        	  	   QINT current = 0;
	        	  	   if(linelength>=50){
	        	  		   for(QINT i=0; i<linelength-49;i++){
	        	  		       current = filestring.Find('}',current);
	        	  		       current ++;
	        	  		   }
	        	  	   }
	        	  	   
	        	  	   //ִ���ַ�Ŀ���
	        	       CQSString strtemp;  
	        	       strtemp.Empty();
	        	       strtemp.AppendData(cqstring.GetDataPtr());
	        	       cqstring.Empty();
	        	  	   //�õ�Դ�ļ��еĲ������
	        	       filestring.GetSubString(cqstring,current,lastlength-current);
	        	       cqstring.AppendData(strtemp);
	        	        
	        	       //ִ��д�ļ�����
	        	  	   file->WriteData(cqstring.GetDataPtr(),cqstring.GetLength());
	        	  }
	        	  delete[] p_string;
	        	  p_string = NULL;
	    	 }else{
	    	     //д�ļ�����
	    	     file->WriteData(cqstring.GetDataPtr(),cqstring.GetLength());
	    	 }
	    }
	    else  //ִ�ж��ļ�����  
	    {
	         //���ļ�����
	    	 QUINT filelength = file->GetLength();
	    	 if(filelength>0){
	    	    LPSTR p_string = new char[filelength];
	    	    file->Read(p_string,filelength);
	    	    CQSString filestring;
	    	    filestring.Empty();
	    	    filestring.AppendData(p_string);
	    	    delete[] p_string;
	    	    p_string = NULL;
	    	    //�õ���¼����
	    	   	QUINT  lastlength = 0;//�ҵ����һ��}��λ��
	    	   	while(filelength>lastlength){
	    	   	    lastlength = filestring.Find("}",lastlength);
	    	   	    lastlength ++;//�ƶ�����һ��δ֪
	    	   	    if(lastlength <= 0)
	    	   	    {	  	    	
	    	   	      break;	  	    	
	    	   	    }
	    	   	}
	    	   	
	    	    cqstring.Empty();
	    	    filestring.GetSubString(cqstring,0,lastlength);
	    	 }
	    }
	}
	
	if(file!=NULL)
	{
	    //ִ���ļ�������
	    file->Close();
	    DELETE(file);
	}
	
	if(cqstring.IsEmpty())
	{
	    return false;
	}
	else
	{
	    return true;
	}
}

LPSTR CMobileSDK::TIntToString(TInt tint)
{
	TBuf16<20> buf;
	buf.Format( _L( "%d" ) , tint);
	return(LPSTR)buf.Ptr();
}

EXPORT_C QVOID CMobileSDK::StringToTBuf(LPSTR source, TDes& buf)
{
	TPtrC8 ptr;
	ptr.Set( (const TUint8*)source , strlen(source));
	buf.Copy(ptr);
}

QVOID CMobileSDK::ClientBodyReceived(const TDesC8& aBodyData)
{
	TBuf<32> desShow;
	desShow.Copy(aBodyData);
	CEikonEnv::InfoWinL(_L("OK"),desShow);
}

void CMobileSDK::ClientEvent(const TDesC& aEventDescription)
{
	
}
